package com.comum.javahomework420242025.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class DownLoadController {
    @GetMapping("/downloadfile/{filename}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
        System.out.println(filename);
        String projectRootPath = System.getProperty("user.dir");
        // 设置文件保存路径，这里以项目的根目录下的uploads文件夹为例
        String uploadDir = Paths.get(projectRootPath, "uploads").toString();
        System.out.println(uploadDir);
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs(); // 如果目录不存在，则创建目录
        Path filePath = Paths.get(uploadDir).resolve(filename); // 构建文件路径
        Resource resource;
        try {
            UrlResource urlResource = new UrlResource(filePath.toUri());
            if (!urlResource.exists()) {
                throw new IOException("文件不存在: " + filename);
            }
            resource = urlResource;
        } catch (MalformedURLException e) {
            throw new RuntimeException("无法下载文件: " + filename, e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String contentType = null;
        try {
            contentType = Files.probeContentType(filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (contentType == null) contentType = "application/octet-stream"; // 默认内容类型
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }
}
